// 智驭安行 - 智慧交通系统主要JavaScript文件
document.addEventListener('DOMContentLoaded', function() {
    // 初始化导航栏激活状态
    initNavigation();
    
    // 初始化交通工具点击事件
    initTransportItems();
    
    // 初始化查询项点击事件
    initQueryItems();
    
    // 初始化地图控制
    initMapControls();
    
    // 初始化仪表盘数据
    initDashboardData();
    
    // 初始化异常行为监测模拟
    initAnomalyDetection();
});

// 导航栏激活状态
function initNavigation() {
    const navLinks = document.querySelectorAll('nav ul li a');
    const currentPath = window.location.pathname;
    
    navLinks.forEach(link => {
        if (link.getAttribute('href') === currentPath || 
            (currentPath === '/' && link.getAttribute('href') === 'index.html')) {
            link.classList.add('active');
        }
        
        link.addEventListener('click', function(e) {
            navLinks.forEach(l => l.classList.remove('active'));
            this.classList.add('active');
        });
    });
}

// 交通工具项点击事件
function initTransportItems() {
    const transportItems = document.querySelectorAll('.transport-item');
    
    transportItems.forEach(item => {
        item.addEventListener('click', function() {
            const transportType = this.getAttribute('data-type');
            
            // 模拟跳转到相应的交通工具监测页面
            if (transportType) {
                window.location.href = `transport-monitor.html?type=${transportType}`;
            } else {
                console.log('未设置交通工具类型');
            }
        });
    });
}

// 查询项点击事件
function initQueryItems() {
    const queryItems = document.querySelectorAll('.query-item');
    
    queryItems.forEach(item => {
        item.addEventListener('click', function() {
            const queryType = this.getAttribute('data-type');
            
            // 模拟跳转到相应的查询页面
            if (queryType) {
                window.location.href = `query.html?type=${queryType}`;
            } else {
                console.log('未设置查询类型');
            }
        });
    });
}

// 地图控制功能
function initMapControls() {
    const zoomInBtn = document.querySelector('.map-controls .zoom-in');
    const zoomOutBtn = document.querySelector('.map-controls .zoom-out');
    const resetBtn = document.querySelector('.map-controls .reset');
    
    if (zoomInBtn && zoomOutBtn && resetBtn) {
        let scale = 1;
        const mapImage = document.querySelector('.map-image img');
        
        zoomInBtn.addEventListener('click', function() {
            scale += 0.1;
            updateMapScale(mapImage, scale);
        });
        
        zoomOutBtn.addEventListener('click', function() {
            scale = Math.max(0.5, scale - 0.1);
            updateMapScale(mapImage, scale);
        });
        
        resetBtn.addEventListener('click', function() {
            scale = 1;
            updateMapScale(mapImage, scale);
            // 重置位置
            mapImage.style.transform = `scale(${scale})`;
            mapImage.style.transformOrigin = 'center center';
        });
        
        // 实现地图拖动功能
        let isDragging = false;
        let startX, startY, initialX = 0, initialY = 0;
        
        mapImage.addEventListener('mousedown', function(e) {
            isDragging = true;
            startX = e.clientX;
            startY = e.clientY;
            initialX = parseInt(mapImage.style.left || 0);
            initialY = parseInt(mapImage.style.top || 0);
            mapImage.style.cursor = 'grabbing';
        });
        
        document.addEventListener('mousemove', function(e) {
            if (!isDragging) return;
            
            const dx = e.clientX - startX;
            const dy = e.clientY - startY;
            
            mapImage.style.left = `${initialX + dx}px`;
            mapImage.style.top = `${initialY + dy}px`;
        });
        
        document.addEventListener('mouseup', function() {
            isDragging = false;
            mapImage.style.cursor = 'grab';
        });
    }
}

// 更新地图缩放
function updateMapScale(mapImage, scale) {
    if (mapImage) {
        mapImage.style.transform = `scale(${scale})`;
    }
}

// 初始化仪表盘数据
function initDashboardData() {
    // 模拟获取实时数据
    updateMetrics();
    
    // 定期更新数据
    setInterval(updateMetrics, 5000);
    
    // 初始化图表
    initCharts();
}

// 更新指标数据
function updateMetrics() {
    const metricValues = document.querySelectorAll('.metric-value');
    
    metricValues.forEach(metric => {
        // 模拟数据变化
        const currentValue = parseInt(metric.textContent);
        const variation = Math.floor(Math.random() * 5) - 2; // -2 到 2 的随机变化
        const newValue = Math.max(0, currentValue + variation);
        
        // 应用数字变化动画
        animateNumberChange(metric, currentValue, newValue);
    });
    
    // 更新告警信息
    updateAlerts();
}

// 数字变化动画
function animateNumberChange(element, start, end) {
    const duration = 1000; // 动画持续时间（毫秒）
    const startTime = performance.now();
    
    function updateNumber(currentTime) {
        const elapsedTime = currentTime - startTime;
        const progress = Math.min(elapsedTime / duration, 1);
        
        const currentValue = Math.floor(start + (end - start) * progress);
        element.textContent = currentValue;
        
        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        }
    }
    
    requestAnimationFrame(updateNumber);
}

// 更新告警信息
function updateAlerts() {
    const alertsContainer = document.querySelector('.alerts');
    
    if (alertsContainer) {
        // 随机决定是否添加新告警
        if (Math.random() > 0.7) {
            const alertTypes = ['info', 'warning', 'danger'];
            const alertMessages = [
                '检测到1号公交车司机疲劳驾驶行为',
                '5号地铁车厢内检测到可疑物品',
                '3号公交车乘客区域检测到异常行为',
                '2号地铁站台人流密度过高',
                '4号公交车司机长时间分心驾驶'
            ];
            
            const alertType = alertTypes[Math.floor(Math.random() * alertTypes.length)];
            const alertMessage = alertMessages[Math.floor(Math.random() * alertMessages.length)];
            
            const alertItem = document.createElement('div');
            alertItem.className = `alert-item ${alertType}`;
            alertItem.innerHTML = `<i class="fas fa-exclamation-circle"></i>${alertMessage}`;
            
            // 添加新告警到顶部
            alertsContainer.prepend(alertItem);
            
            // 限制告警数量，保持最新的5条
            const alerts = alertsContainer.querySelectorAll('.alert-item');
            if (alerts.length > 5) {
                alertsContainer.removeChild(alerts[alerts.length - 1]);
            }
            
            // 添加点击处理告警的功能
            alertItem.addEventListener('click', function() {
                this.style.opacity = '0.5';
                this.style.textDecoration = 'line-through';
                
                // 2秒后移除告警
                setTimeout(() => {
                    this.remove();
                }, 2000);
            });
        }
    }
}

// 初始化图表
function initCharts() {
    // 这里可以集成图表库如Chart.js或ECharts
    // 以下是一个简单的模拟实现
    const chartContainers = document.querySelectorAll('.chart-container');
    
    chartContainers.forEach(container => {
        const placeholder = container.querySelector('.chart-placeholder');
        
        if (placeholder) {
            placeholder.textContent = '图表加载中...';
            
            // 模拟图表加载
            setTimeout(() => {
                placeholder.textContent = '图表已加载（这里实际项目中应集成图表库）';
            }, 1500);
        }
    });
}

// 异常行为监测模拟
function initAnomalyDetection() {
    // 模拟异常行为检测系统
    console.log('异常行为监测系统已初始化');
    
    // 定期检查异常行为
    setInterval(checkForAnomalies, 8000);
}

// 检查异常行为
function checkForAnomalies() {
    // 模拟异常行为检测
    const anomalyTypes = [
        '司机疲劳驾驶',
        '司机分心驾驶',
        '乘客异常行为',
        '车内可疑物品',
        '车辆超载'
    ];
    
    // 随机决定是否触发异常行为告警
    if (Math.random() > 0.7) {
        const anomalyType = anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)];
        const vehicleId = Math.floor(Math.random() * 10) + 1;
        const severity = Math.random() > 0.5 ? '高' : '中';
        
        // 创建告警通知
        createAnomalyNotification(anomalyType, vehicleId, severity);
    }
}

// 创建异常行为告警通知
function createAnomalyNotification(type, vehicleId, severity) {
    // 检查通知容器是否存在，如果不存在则创建
    let notificationContainer = document.querySelector('.notification-container');
    
    if (!notificationContainer) {
        notificationContainer = document.createElement('div');
        notificationContainer.className = 'notification-container';
        notificationContainer.style.position = 'fixed';
        notificationContainer.style.top = '20px';
        notificationContainer.style.right = '20px';
        notificationContainer.style.zIndex = '1000';
        document.body.appendChild(notificationContainer);
    }
    
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${severity === '高' ? 'high' : 'medium'}`;
    notification.style.backgroundColor = severity === '高' ? '#ff4d4d' : '#ffcc00';
    notification.style.color = severity === '高' ? 'white' : 'black';
    notification.style.padding = '15px';
    notification.style.borderRadius = '5px';
    notification.style.marginBottom = '10px';
    notification.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.2)';
    notification.style.display = 'flex';
    notification.style.justifyContent = 'space-between';
    notification.style.alignItems = 'center';
    notification.style.transition = 'all 0.3s ease';
    notification.style.cursor = 'pointer';
    
    // 通知内容
    notification.innerHTML = `
        <div>
            <strong>异常行为告警</strong>
            <p>车辆ID: ${vehicleId} - 检测到${type}</p>
            <p>严重程度: ${severity}</p>
        </div>
        <div class="close-btn" style="font-size: 20px; cursor: pointer;">×</div>
    `;
    
    // 添加到通知容器
    notificationContainer.appendChild(notification);
    
    // 添加关闭按钮事件
    const closeBtn = notification.querySelector('.close-btn');
    closeBtn.addEventListener('click', function(e) {
        e.stopPropagation();
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        
        setTimeout(() => {
            notification.remove();
        }, 300);
    });
    
    // 点击通知跳转到详情页面
    notification.addEventListener('click', function() {
        window.location.href = `anomaly-details.html?id=${vehicleId}&type=${encodeURIComponent(type)}`;
    });
    
    // 5秒后自动消失
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 5000);
}

// 模拟实时数据更新
function simulateRealTimeData() {
    // 这里可以添加WebSocket连接或轮询API的代码
    console.log('实时数据模拟已启动');
    
    // 模拟数据更新
    setInterval(() => {
        // 更新在线车辆数
        updateOnlineVehicles();
        
        // 更新监控状态
        updateMonitoringStatus();
    }, 3000);
}

// 更新在线车辆数
function updateOnlineVehicles() {
    const onlineVehiclesElement = document.querySelector('.online-vehicles');
    
    if (onlineVehiclesElement) {
        const currentValue = parseInt(onlineVehiclesElement.textContent);
        const variation = Math.floor(Math.random() * 3) - 1; // -1 到 1 的随机变化
        const newValue = Math.max(0, currentValue + variation);
        
        onlineVehiclesElement.textContent = newValue;
    }
}

// 更新监控状态
function updateMonitoringStatus() {
    const statusElements = document.querySelectorAll('.status');
    
    statusElements.forEach(status => {
        // 随机决定是否改变状态
        if (Math.random() > 0.9) {
            if (status.classList.contains('active')) {
                status.classList.remove('active');
                status.textContent = '离线';
                status.style.backgroundColor = '#eee';
                status.style.color = '#666';
            } else {
                status.classList.add('active');
                status.textContent = '在线';
                status.style.backgroundColor = '#e6f7e6';
                status.style.color = '#00aa00';
            }
        }
    });
}

// 启动实时数据模拟
simulateRealTimeData();